<template>
  <BaseDialog :title="(!props.item.dictionaryId ? '新增' : '编辑') + '类型'" :handleCancel="handleCancel"
    :dialogVisible="props.dialogVisible">
    <BaseForm type="rule" :handleOk="handleOk" :handleCancel="handleCancel" :items="formItems" v-model:form="ruleForm"
      label-width="100px" :rules="rules" :refresh="handleSearch">
    </BaseForm>
  </BaseDialog>
</template>

<script setup lang="ts">
import { commonService } from '@/api/common'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  /* 字典管理的时候需要见值 */
  showall:{
    type: Boolean,
    default: true,
  }

})
const emit = defineEmits(['update:dialogVisible'])

const formItems =props.showall? ref([
  {
    name: '类型名称',
    key: 'dictionaryName',
    type: 'input',
  },
  {
    name: '排序数字',
    key: 'sortNum',
    type: 'number',
    placeholder: '请输入排序数字，数字越小越靠前',
    min: 0,
  },
]):props.item.dictionaryId?ref([
  {
    name: '类型名称',
    key: 'dictionaryName',
    type: 'input',
  },
 
  {
    name: '排序数字',
    key: 'sortNum',
    type: 'number',
    placeholder: '请输入排序数字，数字越小越靠前',
    min: 0,
  },
]):ref([
  {
    name: '类型名称',
    key: 'dictionaryName',
    type: 'input',
  },
  {
    name: '键',
    key: 'dictionaryKey',
    type: 'input',
  },
  {
    name: '排序数字',
    key: 'sortNum',
    type: 'number',
    placeholder: '请输入排序数字，数字越小越靠前',
    min: 0,
  },
])
const rules = reactive({
  dictionaryName: [{ required: true, message: '请输入', trigger: 'change' }, { max: 255, message: '最长255个字符' }],
  dictionaryKey: [{ required: true, message: '请输入', trigger: 'change' },, { max: 40, message: '最长40个字符' }],
  
})
const ruleForm = ref(props.showall?{
  parentId: 0,
  dictionaryId: '',
  dictionaryName: '',
  sortNum: ref<Number>(),
}:{parentId: 0,
  dictionaryId: '',
  dictionaryName: '',
  dictionaryKey: '',
  dictionaryValue: '',
  sortNum: ref<Number>(),})
const handleOk = () => {
  if (props.item.dictionaryId) {
    return commonService.editDictionary({
      data: { ...ruleForm.value },
    })
  } else {
    return commonService.addDictionary(props.showall?{
      data: {
        ...ruleForm.value,
        
      },
    }:{
      data: {
        ...ruleForm.value,
        dictionaryValue: ruleForm.value.dictionaryKey,
      },
    })
  }
}

const handleCancel = () => {
  emit('update:dialogVisible', false)
}
onMounted(() => {
  if (props.item.dictionaryId) {
    ruleForm.value.dictionaryId = props.item.dictionaryId
    ruleForm.value.dictionaryName = props.item.dictionaryName
      
    if(!props.showall){
      ruleForm.value.dictionaryKey = props.item.dictionaryKey
      ruleForm.value.dictionaryValue = props.item.dictionaryValue
    }
    ruleForm.value.sortNum = props.item.sortNum
  }
  //console.log()
})
</script>

<style lang="scss" scoped></style>
